package com.labprog.oncapintada.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.labprog.oncapintada.exceptions.ErroGeralException;
import com.labprog.oncapintada.exceptions.ProdutoNaoEncontradoException;
import com.labprog.oncapintada.models.Produto;
import com.labprog.oncapintada.persistencia.PersistenciaProduto;

public class ImageServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		 response.setHeader("Cache-Control", "no-store");
		 response.setHeader("Pragma", "no-cache");
		 response.setDateHeader("Expires", 0);
		 response.setContentType("image/jpeg");
		 
		 Integer id = Integer.parseInt(request.getParameter("id"));
		 
		 Produto produto = new Produto(id);
		 
		 try {
			InputStream is = new PersistenciaProduto().obterFotoProduto(produto);
			ServletOutputStream out = response.getOutputStream();
			 BufferedImage img = ImageIO.read(is);
			 ImageIO.write(img, "jpeg", response.getOutputStream());
			 out.flush();
			 out.close();
		} catch (ProdutoNaoEncontradoException e) {
			e.printStackTrace();
		} catch (ErroGeralException e) {
			e.printStackTrace();
		}
	}
}
